import os
import json


def load_config(config_name):
    config_path = os.path.join(os.path.dirname(__file__), "..", "..", "Config", f"{config_name}.json")
    if os.path.exists(config_path):
        with open(config_path, "r", encoding="utf-8") as f:
            try:
                config_content = json.load(f)
                return config_content
            except json.JSONDecodeError as e:
                raise
    else:
        raise FileNotFoundError(f"配置文件未找到: {config_path}")


def get_model_config(model_name):
    config = load_config("Config")
    if "Model" in config:
        model_config = config["Model"]
        # 首先从环境变量中获取 API 密钥
        api_key = os.getenv("OPENAI_API_KEY", "")
        if not api_key:
            api_key = model_config.get("api_key", "")
        model_config["api_key"] = api_key
        return model_config
    else:
        raise ValueError(f"模型配置未找到: {model_name}")


def get_supported_models():
    return load_config("model")
